using System.Collections.Specialized;
using System.Text;
using System.Web;
using System;

namespace Pegasus.Web
{
    /// <summary>
    /// Creates a QueryString collection whose collection is editable.
    /// This is used for modifying request querystrings by adding/removing pieces.
    /// </summary>
    public class QueryStringCollection : NameValueCollection
    {
        /// <summary>
        /// Constructor that initializes an empty QSC.
        /// </summary>
        /// <param name="useCurrentRequest">Specifies whether the QSC should use the current context query string.</param>
        public QueryStringCollection( bool useCurrentRequest )
        {
            if( useCurrentRequest )
            {
                Add( HttpContext.Current.Request.QueryString );
            }
        }

        /// <summary>
        /// Constructor that uses the current contexts query string.
        /// </summary>
        public QueryStringCollection() : this( true ) { }

        /// <summary>
        /// Constructor that uses the name value collection given.
        /// </summary>
        /// <param name="queryString"></param>
        public QueryStringCollection( NameValueCollection queryString ) : base( queryString ) { }

        /// <summary>
        /// Constructor that uses the string given.
        /// </summary>
        /// <param name="queryString">A query string string.</param>
        public QueryStringCollection( string queryString ) : base()
        {
            if( !string.IsNullOrEmpty( queryString ) )
            {
                foreach( string pair in queryString.Split( new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries ) )
                {
                    string[] pieces = pair.Split( '=' );
                    Add( pieces[ 0 ], HttpUtility.UrlDecode( pieces[ 1 ] ) );
                }
            }
        }

        /// <summary>
        /// Returns a usuable querystring with the internal name value collection.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            foreach( string key in Keys )
            {
                sb.AppendFormat( "{0}={1}&", key, HttpUtility.UrlEncode( this[ key ] ) );
            }

            if( sb.Length > 0 )
            {
                sb.Remove( sb.Length - 1, 1 );
            }

            return sb.ToString();
        }
    }
}